package com.qs.home.ui.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.databinding.Observable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.baidu.ocr.demo.FileUtil;
import com.baidu.ocr.demo.RecognizeService;
import com.baidu.ocr.sdk.exception.OCRError;
import com.google.gson.Gson;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.permissions.RxPermissions;
import com.qs.base.base.BaseMyActivity;
import com.qs.base.global.SPKeyGlobal;
import com.qs.base.interfaces.DialogListener;
import com.qs.base.router.RouterActivityPath;
import com.qs.base.utils.CommomDialog;
import com.qs.home.BR;
import com.qs.home.R;
import com.qs.home.databinding.HomeHomeActivityBinding;
import com.qs.home.entity.TextResultEntity;
import com.qs.home.ui.VM.HomeItemViewModel;
import com.qs.home.ui.VM.HomeViewModel;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.SPUtils;
import me.goldze.mvvmhabit.utils.StringUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;

/**
 * 主页
 *
 * @Author ltzz
 * @Date 2019/8/8
 */
@Route(path = RouterActivityPath.Home.HOME_MAIN)
public class HomeActivity extends BaseMyActivity<HomeHomeActivityBinding, HomeViewModel> {
    //提示显示type
    private boolean type = false;

    @Override
    protected boolean statusBarDarkFont() {
        return false;
    }

    @Override
    protected View titleLayout() {
        return binding.my;
    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.home_home_activity;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //显示提示

        KLog.e("ssss334 "+SPUtils.getInstance().getBoolean(SPKeyGlobal.MAIN_HINT, false));
        if (!SPUtils.getInstance().getBoolean(SPKeyGlobal.MAIN_HINT, false)){
            show();
        }

        RxPermissions permissions = new RxPermissions(this);
        permissions.request(perms).subscribe(new Observer<Boolean>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(Boolean aBoolean) {
                if (aBoolean) {
                } else {
                    ToastUtils.showShort("拒绝授权部分功能将无法使用！");
                }
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onComplete() {
            }
        });

        RecognizeService.getToken(this, new RecognizeService.ServiceListener() {
            @Override
            public void onResult(String result) {
                String token = result;
                KLog.e(token);
            }

            @Override
            public void onError(OCRError err) {
//                ToastUtils.showLong("初始化token失败！");
                Log.d("adfadfafd" ,"初始化token失败" +err.getErrorCode() );
                Log.d("adfadfafd" ,"初始化token失败" +err.getMessage() );
                KLog.e(err.getErrorCode());
            }
        });
        //写入数据
        viewModel.observableList.clear();
        if (viewModel.homeContent.get() != null && viewModel.homeContent.get().size() > 0) {
            for (int i = 0; i < viewModel.homeContent.get().size(); i++)
                viewModel.observableList.add(new HomeItemViewModel(viewModel, viewModel.homeContent.get().get(i)));
        }


    }

    CommomDialog commomDialog;

    //次数提示信息
    public void show() {
        commomDialog = showHint("每次识别会消耗一次识别次数，普通用户可免费识别十次，会员无限制。", "", R.layout.home_hint_dialog, null, null, new DialogListener() {
            @Override
            public void complete(Dialog dialog, boolean confirm) {
                dialog.dismiss();
                if (!confirm) {
                    //开通会员
                    ARouter.getInstance().build(RouterActivityPath.User.MEMBER_CENTER_ACTIVITY).navigation();
                }
                //储存状态信息
                SPUtils.getInstance().put(SPKeyGlobal.MAIN_HINT, type);
            }
        });
        final ImageView select = commomDialog.findViewById(R.id.select);
        commomDialog.findViewById(R.id.remind).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                type = !type;

                //储存状态信息
                SPUtils.getInstance().put(SPKeyGlobal.MAIN_HINT, type);
                select.setSelected(type);
            }
        });
    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();
        //图片选择
        viewModel.uc.selectImg.addOnPropertyChangedCallback(new Observable.OnPropertyChangedCallback() {
            @Override
            public void onPropertyChanged(Observable sender, int propertyId) {
                PictureSelector.create(HomeActivity.this)
                        .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
//                        .theme()//主题样式(不设置为默认样式) 也可参考demo values/styles下 例如：R.style.picture.white.style
//                        .maxSelectNum(1)// 最大图片选择数量 int
//                        .minSelectNum()// 最小选择数量 int
                        .imageSpanCount(3)// 每行显示个数 int
                        .selectionMode(PictureConfig.SINGLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                        .previewImage(true)// 是否可预览图片 true or false
//                        .previewVideo()// 是否可预览视频 true or false
//                        .enablePreviewAudio() // 是否可播放音频 true or false
                        .isCamera(viewModel.havePhoto)// 是否显示拍照按钮 true or false
                        .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                        .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                        .sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                        .setOutputCameraPath("/CustomPath")// 自定义拍照保存路径,可不填
                        .enableCrop(true)// 是否裁剪 true or false
                        .compress(true)// 是否压缩 true or false
//                        .glideOverride()// int glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
//                        .withAspectRatio(3, 2)// int 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
//                        .hideBottomControls()// 是否显示uCrop工具栏，默认不显示 true or false
                        .isGif(false)// 是否显示gif图片 true or false
//                        .compressSavePath(getPath())//压缩图片保存地址
                        .freeStyleCropEnabled(true)// 裁剪框是否可拖拽 true or false
                        .circleDimmedLayer(false)// 是否圆形裁剪 true or false
                        .showCropFrame(true)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false   true or false
                        .showCropGrid(true)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false    true or false
                        .openClickSound(false)// 是否开启点击声音 true or false
//                        .selectionMedia()// 是否传入已选图片 List<LocalMedia> list
                        .previewEggs(true)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false
//                        .cropCompressQuality()// 裁剪压缩质量 默认90 int
                        .minimumCompressSize(100)// 小于100kb的图片不压缩
                        .synOrAsy(true)//同步true或异步false 压缩 默认同步
//                        .cropWH()// 裁剪宽高比，设置如果大于图片本身宽高则无效 int
                        .rotateEnabled(false) // 裁剪是否可旋转图片 true or false
                        .scaleEnabled(false)// 裁剪是否可放大缩小图片 true or false
//                        .videoQuality()// 视频录制质量 0 or 1 int
//                        .videoMaxSecond(15)// 显示多少秒以内的视频or音频也可适用 int
//                        .videoMinSecond(10)// 显示多少秒以内的视频or音频也可适用 int
//                        .recordVideoSecond()//视频秒数录制 默认60s int
                        .isDragFrame(true)// 是否可拖动裁剪框(固定)
                        .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
            }
        });
        //拍照识别
        viewModel.uc.photoDiscernUc.addOnPropertyChangedCallback(new Observable.OnPropertyChangedCallback() {
            @Override
            public void onPropertyChanged(Observable sender, int propertyId) {
                viewModel.showDialog();
                RecognizeService.recGeneralBasic(HomeActivity.this, FileUtil.getSaveFile(getApplicationContext()).getAbsolutePath(), new RecognizeService.ServiceListener() {
                    @Override
                    public void onResult(String result) {
                        viewModel.dismissDialog();
                        KLog.e("拍照识别：" + result);
                        Gson gson = new Gson();
                        try {
                            TextResultEntity textResult = gson.fromJson(result, TextResultEntity.class);
                            textResult.setFilePath(FileUtil.getSaveFile(getApplicationContext()).getAbsolutePath());

                            //消耗识别次数
                            String seeNumberStr = SPUtils.getInstance().getString(SPKeyGlobal.SEE_NUMBER, "0");
                            int x = Integer.parseInt(seeNumberStr);
                            SPUtils.getInstance().put(SPKeyGlobal.SEE_NUMBER, ((x - 1) < 0 ? 0 : (x - 1)) + "");
                            ARouter.getInstance().build(RouterActivityPath.Home.IDENTIFY_DETAILS).withString("textResult", gson.toJson(textResult)).navigation();
                        } catch (Exception e) {
                            ToastUtils.showShort("请重试....");
                        }
                    }

                    @Override
                    public void onError(OCRError err) {
                        viewModel.dismissDialog();
                        KLog.e("拍照识别：" + "识别失败，请重试...");
                        ToastUtils.showShort("识别失败，请重试...");
                    }
                });
            }
        });
        //票据识别
        viewModel.uc.noteDiscernUc.addOnPropertyChangedCallback(new Observable.OnPropertyChangedCallback() {
            @Override
            public void onPropertyChanged(Observable sender, int propertyId) {
                viewModel.showDialog();
                RecognizeService.recReceipt(HomeActivity.this, FileUtil.getSaveFile(getApplicationContext()).getAbsolutePath(), new RecognizeService.ServiceListener() {
                    @Override
                    public void onResult(String result) {
                        viewModel.dismissDialog();
                        KLog.e("票据识别：" + result);
                        Gson gson = new Gson();
                        try {
                            TextResultEntity textResult = gson.fromJson(result, TextResultEntity.class);
                            textResult.setFilePath(FileUtil.getSaveFile(getApplicationContext()).getAbsolutePath());

                            //消耗识别次数
                            String seeNumberStr = SPUtils.getInstance().getString(SPKeyGlobal.SEE_NUMBER, "0");
                            int x = Integer.parseInt(seeNumberStr);
                            SPUtils.getInstance().put(SPKeyGlobal.SEE_NUMBER, ((x - 1) < 0 ? 0 : (x - 1)) + "");
                            ARouter.getInstance().build(RouterActivityPath.Home.IDENTIFY_DETAILS).withString("textResult", gson.toJson(textResult)).navigation();
                        } catch (Exception e) {
                            ToastUtils.showShort("请重试....");
                        }
                    }

                    @Override
                    public void onError(OCRError err) {
                        viewModel.dismissDialog();
                        KLog.e("拍照识别：" + "识别失败，请重试...");
                        ToastUtils.showShort("识别失败，请重试...");
                    }
                });
            }
        });
    }

    int num = 0;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    //图片选择
                    final List<LocalMedia> images = PictureSelector.obtainMultipleResult(data);
                    //原地址
//                    images.get(0).getPath();
                    //压缩
//                    images.get(0).getCompressPath();
                    //裁剪地址
                    images.get(0).getCutPath();
                    KLog.e(data);
                    if (images != null && images.size() > 0) {
                        //是否会员
                        boolean isOk = false;
                        if (!StringUtils.isTrimEmpty(SPUtils.getInstance().getString(SPKeyGlobal.USER_ID))) {
                            //用户已登录
                            //查看是否是会员
                            String date = SPUtils.getInstance().getString(SPKeyGlobal.USER_DATE, "");
                            if (!StringUtils.isTrimEmpty(date)) {
                                if (Float.parseFloat(date) > 0) {
                                    isOk = true;
                                }
                            }
                        }
                        if (!isOk) {
                            String seeNumberStr = SPUtils.getInstance().getString(SPKeyGlobal.SEE_NUMBER, "0");
                            int x = (int) Float.parseFloat(seeNumberStr);
                            if (x <= 0) {
                                ToastUtils.showShort("识别次数已用完");
                                return;
                            }
                        }
                        viewModel.showDialog();
                        final List<TextResultEntity> textResults = new ArrayList<>();
                        num = 0;
                        final Gson gson = new Gson();
                        for (int i = 0; i < images.size(); i++) {
                            RecognizeService.recGeneralBasic(HomeActivity.this, images.get(i).getCutPath(), new RecognizeService.ServiceListener() {
                                @Override
                                public void onResult(String result) {
                                    KLog.e("图片选择：" + result);
                                    TextResultEntity textResult = gson.fromJson(result, TextResultEntity.class);
                                    textResult.setFilePath(images.get(num).getCutPath());
                                    textResults.add(textResult);
                                    num = num + 1;
                                    if (num == images.size()) {
                                        //识别完成
                                        viewModel.dismissDialog();
                                        ARouter.getInstance().build(RouterActivityPath.Home.IDENTIFY_RESULTS).withString("textResults", gson.toJson(textResults)).navigation();
                                    }
                                }

                                @Override
                                public void onError(OCRError err) {
                                    num = num + 1;
                                    KLog.e("图片选择：" + "识别失败，请重试...");
                                    if (num == images.size()) {
                                        //识别完成
                                        viewModel.dismissDialog();
                                        ARouter.getInstance().build(RouterActivityPath.Home.IDENTIFY_RESULTS).withString("textResults", gson.toJson(textResults)).navigation();
                                    }
                                }
                            });
                        }
                    }
                    break;
            }
        }
    }

    private static boolean mBackKeyPressed = false;//记录是否有首次按键

    @Override
    public void onBackPressed() {
        if (!mBackKeyPressed) {
            ToastUtils.showShort("再按一次退出程序");
            mBackKeyPressed = true;
            new Timer().schedule(new TimerTask() {//延时两秒，如果超出则擦错第一次按键记录
                @Override
                public void run() {
                    mBackKeyPressed = false;
                }
            }, 2000);
        } else {//退出程序
            this.finish();
            System.exit(0);
        }
    }

    String[] perms = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};
}
